package com.jcw.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcw.common.R;
import com.jcw.domain.Category;
import com.jcw.domain.Dish;
import com.jcw.service.CategoryService;
import com.jcw.mapper.CategoryMapper;
import com.jcw.service.DishService;
import com.jcw.service.SetmealService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author JCW
 * @description 针对表【category(菜品及套餐分类)】的数据库操作Service实现
 * @createDate 2023-03-27 22:39:09
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {

    @Resource
    private DishService dishService;

    @Resource
    private SetmealService setmealService;

    @Override
    public R<Page> pagination(int page, int pageSize) {
        Page<Category> pageInfo = new Page<>(page, pageSize);
        query().orderByAsc("sort").page(pageInfo);
        return R.success(pageInfo);
    }

    @Override
    public R<String> addCategory(Category category) {
        boolean results = save(category);
        return results ? R.success("添加成功") : R.error("添加失败");
    }

    @Override
    public R<String> editCategory(Category category) {
        boolean results = updateById(category);
        return results ? R.success("修改成功") : R.error("修改失败");
    }

    @Override
    public R<String> removeCategory(Long ids) {
        Long count = dishService.query().eq("category_id", ids).count();
        if (count > 0) {
            return R.error("菜品关联，不可删除");
        }
        if (setmealService.query().eq("category_id", ids).count() > 0) {
            return R.error("套餐关联，不可删除");
        }
        return R.success("删除成功");
    }

    @Override
    public R<List> getCategoryList(Integer type) {
        if (type == null){
            List<Category> categoryList = list();
            return R.success(categoryList);
        }

        List<Category> categoryList = query().eq("type", type).list();
        if (categoryList.size() < 1) {
            return R.error("菜品获取失败");
        }
        return R.success(categoryList);
    }
}




